package be.ipl.finito.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.finito.exceptions.JoueurExistantException;
import be.ipl.finito.exceptions.MotDePasseException;
import be.ipl.finito.usecases.GestionJoueur;

/**
 * Servlet implementation class Connexion
 */
public class Connexion extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionJoueur gestionJoueurs;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	
	
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getNamedDispatcher("index.html")
		.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String pseudo = request.getParameter("pseudo");
		String motDePasse = request.getParameter("motDePasse");

		if (pseudo == null || motDePasse == null) {
			request.setAttribute("message", "Pseudo et/ou mot de passe vide");
			request.setAttribute("pMessage", "messagePasOk");
			this.getServletContext().getNamedDispatcher("index.html").forward(request, response);
			return;
		}
		try {
			if (gestionJoueurs.seConnecter(pseudo, motDePasse) != null) {
				HttpSession httpSession = request.getSession();
				synchronized (httpSession) {
					httpSession.setAttribute("pseudo", pseudo);
					httpSession.setAttribute("Connecte", true);
				}
				this.getServletContext().getNamedDispatcher("accueil.html").forward(request, response);
			} else {
				request.setAttribute("message", "Pseudo et/ou mot de passe incorrect");
				request.setAttribute("pMessage", "messagePasOk");
				this.getServletContext().getNamedDispatcher("index.html").forward(request, response);
			}
		} catch (EJBException e) {
			request.setAttribute("message", "Pseudo et/ou mot de passe incorrect");
			request.setAttribute("pMessage", "messagePasOk");
			this.getServletContext().getNamedDispatcher("index.html").forward(request, response);
		}
	}
}
